/**
 * Created by hjqi on 2016/2/12.
 */

var user_collection_name = require('../config/config').config.mongodb.user_collection;
var mongodb = require('../../db/mongodb');
var __db = new mongodb(user_collection_name);
var qs = require('querystring');
var url = require('url');
var OAuthMgr = require('./oauth_mgr');
var st2urlMap = {};
var logger = require('../log4js/log4js').logger('oauth2');

exports.getToken = function (req, res) {

    //var requrl = url.parse(req.url);
    var param = req.query;
    var oauth2 = undefined;
    oauth2 = OAuthMgr.getOAuth(param.type);

    if (oauth2 !== undefined) {

        //TODO 302 to authURL
        var _urlAndSt = oauth2.getReqAuthUrlAndSt();

        res.writeHead(200, {
            'Content-Type': 'application/json'
        });
        res.end(JSON.stringify({'url':_urlAndSt.url}));
        st2urlMap[_urlAndSt.st] = {};
        st2urlMap[_urlAndSt.st].org_url = req.originalUrl;
        st2urlMap[_urlAndSt.st].usr = param;
    } else {
        res.writeHead(200, {
            'Content-Type': 'text/html'
        });
        res.end('not found type');
        return;
    }


}

exports.oauthCallback = function (req, res, requrl) {
    var db = req.db;
    var requrl = url.parse(req.url);
    var qsObj = qs.parse(requrl.query);
    var _ret_st = qsObj.state;
    var _url = st2urlMap[_ret_st].org_url;
    var oauth2 = undefined;
    if (req.url.indexOf('github') !== -1) {
        oauth2 = OAuthMgr.getOAuth('github');
    } else if (req.url.indexOf('bitbucket') !== -1) {
        oauth2 = OAuthMgr.getOAuth('bitbucket');
    } else {
        res.end();
        return;
    }

    if (oauth2 !== undefined) {
        /** Obtaining access_token */
        oauth2._oauth2.getOAuthAccessToken(
            qsObj.code,
            oauth2._accessTokenParam,
            function (e, access_token, refresh_token, results) {
               /* if (e) {
                    console.log(e);
                    res.end(e);
                } else */if (e || results.error) {
                    /*console.log(results);
                    res.end(JSON.stringify(results));*/
                    var _err = e===undefined?results:e;
                    logger.debug('get access token error:['+JSON.stringify(_err) +']')
                    var _usr = st2urlMap[_ret_st].usr;
                    if(req.cookies.getTag !== undefined){
                        res.writeHead(302, {
                            'Content-Type': 'text/html',
                            //TODO replace hardcode url
                            'Location': "/cp/buildlist/"+req.cookies.getTag
                        });
                    }else{
                        res.writeHead(302, {
                            'Content-Type': 'text/html',
                            //TODO replace hardcode url
                            'Location': "/cp/buildlist/modal/"+_usr.type
                        });
                    }
                    res.end();
                }
                else {
                    console.log('Obtained access_token: ', access_token);
                    var _usr = st2urlMap[_ret_st].usr;
                    _usr.token = access_token;
                    __db.insert(db, _usr, function (err) {
                        if (err)
                            res.send(err.message);
                        else {
                            console.log(req.cookies.getTag);
                            if(req.cookies.getTag !== undefined){
                                res.writeHead(302, {
                                    'Content-Type': 'text/html',
                                    //TODO replace hardcode url
                                    'Location': "/cp/buildlist/"+req.cookies.getTag
                                });
                            }else{
                                res.writeHead(302, {
                                    'Content-Type': 'text/html',
                                    //TODO replace hardcode url
                                    'Location': "/cp/buildlist/modal/"+_usr.type
                                });
                            }

                            res.end();
                        }
                    });
                }
            });
    } else {
        res.end('error');
        return;
    }
}

//TODO add source module replace proxy mode